package com.cgsrp.cgsrp_shopping.service.impl;

import com.cgsrp.cgsrp_baby.domain.Message;
import com.cgsrp.cgsrp_baby.service.MessageService;
import com.cgsrp.cgsrp_community.domain.Blog;
import com.cgsrp.cgsrp_shopping.dao.OrderCartMapper;
import com.cgsrp.cgsrp_shopping.dao.ProductMapper;
import com.cgsrp.cgsrp_shopping.dao.ShoppingCartMapper;
import com.cgsrp.cgsrp_shopping.domain.*;
import com.cgsrp.cgsrp_shopping.service.UserWalletService;
import com.cgsrp.cgsrp_user_province.domain.Provinces;
import com.cgsrp.cgsrp_user_province.service.ProvincesService;
import com.cgsrp.utils.Result;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import com.cgsrp.cgsrp_shopping.dao.OrderMapper;
import com.cgsrp.cgsrp_shopping.service.OrderService;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService{

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private OrderCartMapper orderCartMapper;

    @Resource
    private ShoppingCartMapper shoppingCartMapper;

    @Resource
    private ProductMapper productMapper;

    @Resource
    private ProvincesService provincesService;

    @Resource
    private MessageService messageService;

    @Resource
    private UserWalletService walletService;


    @Resource
    private RedisTemplate redisTemplate;



    @Override
    public int deleteByPrimaryKey(Long id) {
        int i = orderMapper.deleteByPrimaryKey(id);
        redisTemplate.delete("order");
        return i;
    }

    @Override
    public int insert(Order record) {
        int i = orderMapper.insert(record);
        redisTemplate.delete("order");
        return i;
    }

    @Override
    public int insertSelective(Order record) {
        int i = orderMapper.insertSelective(record);
        redisTemplate.delete("order");
        return i;
    }

    @Override
    public Order selectByPrimaryKey(Long id) {
        return orderMapper.selectByPrimaryKey(id);
    }

    @Override
    public int updateByPrimaryKeySelective(Order record) {
        int i = orderMapper.updateByPrimaryKeySelective(record);
        redisTemplate.delete("order");
        return i;
    }

    @Override
    public int updateByPrimaryKey(Order record) {
        int i = orderMapper.updateByPrimaryKey(record);
        redisTemplate.delete("order");
        return i;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result creatOrder(int[] ids, Integer userId, Double totalCost) {
        for (int id : ids) {
            ShoppingCart shoppingCart = shoppingCartMapper.selectByPrimaryKey(id);
            Product product = productMapper.selectByPrimaryKey(shoppingCart.getProductId());
            if (product.getNumber()<shoppingCart.getNumber()){
                return Result.failure("创建订单失败，"+product.getName()+"库存不足");
            }else {
                product.setNumber(product.getNumber()-shoppingCart.getNumber());
                productMapper.updateNumber(product);
            }
        }
        Order order = new Order();
        order.setCost(new BigDecimal(totalCost));
        order.setUserId(userId);
        order.setCreatTime(new Date());
        order.setState(0);
        int i = orderMapper.insert(order);
        for (int id : ids) {
            OrderCart orderCart = new OrderCart();
            orderCart.setCartId(id);
            orderCart.setOrderId(order.getId());
            orderCartMapper.insert(orderCart);
            ShoppingCart shoppingCart = new ShoppingCart();
            shoppingCart.setId(id);
            shoppingCart.setState(1);
            shoppingCartMapper.updateByPrimaryKeySelective(shoppingCart);
        }
        if (1>0){
            redisTemplate.delete("order");
        }
        return i>0?Result.success("生成订单成功,请前往订单页面查看"):Result.failure("生成订单失败");
    }

    @Override
    public Result list(int userId, Integer curPage, Integer pageSize) {
        HashOperations ops = redisTemplate.opsForHash();
        // List<Order> list = orderMapper.findByUserId(userId);
        List<Order> list1 = ops.values("order");
        if (list1.isEmpty()){
            list1=orderMapper.findAll();
            list1.sort(Comparator.comparingLong(Order::getId));
            for (Order order : list1) {
                ops.put("order",order.getId(),order);
            }
        }
        List<Order> list=new ArrayList<>();
        for (Order order : list1) {
            if (order.getUserId()==userId){
                list.add(order);
            }
        }
        list.sort(Comparator.comparing(Order::getCreatTime).reversed());
        List<Order> result;
        if (pageSize<list.size()-(curPage-1)*pageSize){
            result= list.subList((curPage - 1) * pageSize, (curPage - 1) * pageSize + pageSize);
        }else {
            result=list.subList((curPage - 1) * pageSize, list.size());
        }
        PageInfo<Order> pageInfo = new PageInfo<>(result);
        pageInfo.setTotal(list.size());
        PageHelper.startPage(curPage, pageSize);
        return Result.suc("查询成功",pageInfo);
    }

    @Override
    public int userAfterPay(String orderId,String userId) {
        try {
            List<Order> byUserId = orderMapper.findByUserId(Integer.parseInt(userId));
            for (Order order : byUserId) {
                if (order.getId()==Long.parseLong(orderId)){
                    for (ShoppingCart shoppingCart : order.getShoppingCarts()) {
                        Provinces provinces=provincesService.findById(order.getProvinceId());
                        Integer creatBy = shoppingCart.getProduct().getCreatBy();
                        Message message = new Message();
                        message.setUserId(creatBy);
                        message.setState(0);
                        message.setType(3);
                        message.setMessage("买家已付款，地址为："+provinces.getMergername()+"详细地址："+order.getAddress()+"。用户手机号："+order.getPhone()+"。用户昵称："+order.getName()+"。请立即发货！");
                        message.setCreattime(new Date());
                        message.setCreatby("系统");
                        message.setOrderId(Long.parseLong(orderId));
                        messageService.insert(message);
                    }
                }
            }
            long id = Long.parseLong(orderId);
            Order order = orderMapper.selectByPrimaryKey(id);
            order.setState(1);
            order.setPayTime(new Date());
            int i = orderMapper.updateByPrimaryKey(order);
            if (i>0){
                redisTemplate.delete("order");
            }
            return i;
        } catch (NumberFormatException e) {
            throw new NumberFormatException();
        }
    }

    @Override
    public Result update(Order order) {
        redisTemplate.delete("order");
        return orderMapper.update(order)>0?Result.success("成功"):Result.failure("更新订单状态失败");
    }

    @Override
    public Result cancel(Long id) {
        redisTemplate.delete("order");
        return orderMapper.cancel(id)>0?Result.success("取消成功"):Result.failure("取消失败");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result confirmReceipt(Order order, int[] creatByIds) {
        int i = orderMapper.updateState(order.getId());
        redisTemplate.delete("order");
        for (int creatById : creatByIds) {
            ShoppingCart shoppingCart = shoppingCartMapper.findById(creatById);
            UserWallet userWallet = walletService.selectByUserId(shoppingCart.getProduct().getCreatBy());
            if (userWallet==null){
                UserWallet userWallet1 = new UserWallet();
                userWallet1.setBalance(shoppingCart.getCost().multiply(new BigDecimal("0.98")).setScale(2, RoundingMode.HALF_UP));
                userWallet1.setPoint(1);
                userWallet1.setUserId(shoppingCart.getProduct().getCreatBy());
                walletService.insert(userWallet1);
            }else {
                userWallet.setBalance(userWallet.getBalance().add(shoppingCart.getCost().multiply(new BigDecimal("0.98")).setScale(2, RoundingMode.HALF_UP)));
                userWallet.setPoint(userWallet.getPoint()+1);
                walletService.update(userWallet);
            }
            Message message = new Message();
            message.setUserId(shoppingCart.getProduct().getCreatBy());
            message.setState(0);
            message.setType(1);
            message.setMessage("买家已收到商品，资金已入账，请查收");
            message.setCreattime(new Date());
            message.setCreatby("系统");
            messageService.insert(message);
        }
        return i>0?Result.success("确认收货成功"):Result.failure("确认收货失败");
    }

    @Override
    public Result deliver(Long orderId, Integer messageId,String trackNum) {
        int i = orderMapper.deliverByOrderId(orderId);
        Order order = orderMapper.selectByPrimaryKey(orderId);
        Message message = new Message();
        message.setState(0);
        message.setType(1);
        message.setCreatby("系统");
        message.setCreattime(new Date());
        message.setUserId(order.getUserId());
        message.setMessage("订单："+orderId+"已发货,快递单号为："+trackNum);
        messageService.insert(message);
        messageService.updateType(messageId,4);
        redisTemplate.delete("order");
        return messageService.updateState(messageId,1)>0?Result.success("发货成功"):Result.failure("发货失败");
    }
}
